<?php

namespace backend\modules\mysql\controllers;

use backend\modules\mysql\models\ServersMysql;
use Yii;
use backend\modules\mysql\models\MysqlStatus;
use backend\modules\mysql\models\MysqlStatusSearch;
use backend\modules\mysql\models\MysqlStatusHistory;
use backend\modules\os\models\OsStatusHistory;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\web\ForbiddenHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;


/**
 * StatusController implements the CRUD actions for MysqlStatus model.
 */
class StatusController extends BaseController
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@']
                    ]
                ]
            ],
        ];
    }

    /**
     * Lists all MysqlStatus models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new MysqlStatusSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single MysqlStatus model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($server)
    {
        $server_array = explode('-',$server);
        $host = $server_array[0];
        $port = $server_array[1];

        $time_interval = 1800;
        $end = 0;
        $start_time = date('YmdHi',(time()-$end-$time_interval));
        $end_time = date('YmdHi',(time()-$end));
        $chart_data = MysqlStatusHistory::find()->where((['host' => $host,'port'=>$port]))->addSelect(['create_time','threads_running','threads_waits','queries_persecond','transaction_persecond'])->andFilterWhere(['>=', 'YmdHi', $start_time])->andFilterWhere(['<=', 'YmdHi', $end_time])->all();
        return $this->render('view', [
            'model' => $this->findModel($server),
            'chart_data' => $chart_data,
        ]);
    }


    /**
     * Finds the MysqlStatus model based on its host and port value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param char $server
     * @return MysqlStatus the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($server)
    {
        $server_array = explode('-',$server);
        $host = $server_array[0];
        $port = $server_array[1];
        if (($model = MysqlStatus::find()->where(['host' => $host,'port'=>$port])->one()) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }


    function actionResource($server){
        return $this->render('resource', [
            'model' => $this->findModel($server),
        ]);
    }

    function actionPerformance($server){
        return $this->render('performance', [
            'model' => $this->findModel($server),
        ]);
    }

    function actionChart(){
        if($post = Yii::$app->request->post()){
            $host = $post['MysqlStatus']['host'];
            $port = $post['MysqlStatus']['port'];
            $time_from = $post['time_from'];
            $time_to = $post['time_to'];
            $start_time = date('YmdHi',strtotime($time_from));
            $end_time = date('YmdHi',strtotime($time_to));
            $time_interval = 0;

        }
        else{
            $server = Yii::$app->getRequest()->get()['server'];
            $server_array = explode('-',$server);
            $host = $server_array[0];
            $port = $server_array[1];

            $time_interval = Yii::$app->getRequest()->get()['time_interval'];
            $end = Yii::$app->getRequest()->get()['end'];
            $start_time = date('YmdHi',(time()-$end-$time_interval));
            $end_time = date('YmdHi',(time()-$end));
            $time_from = date('Y-m-d',time()-3600*24);
            $time_to = date('Y-m-d',time());
        }



        //echo $start_time;exit;
        if (($model = MysqlStatus::findOne(['host' => $host,'port'=>$port])) !== null) {
            //$chart_data = MysqlStatusHistory::find()->where((['host' => $host,'port'=>$port]))->addSelect(['create_time','connect','max_connections','threads_connected','threads_running','threads_waits','queries_persecond','transaction_persecond','com_select_persecond','com_insert_persecond','com_update_persecond','com_delete_persecond','com_commit_persecond','com_rollback_persecond','bytes_received_persecond','bytes_sent_persecond','innodb_rows_read_persecond','innodb_rows_inserted_persecond','innodb_rows_updated_persecond','innodb_rows_deleted_persecond'])->andFilterWhere(['>=', 'YmdHi', $start_time])->andFilterWhere(['<=', 'YmdHi', $end_time])->all();
            $chart_data = MysqlStatusHistory::find()->joinWith('servers')->where((['mysql_status_history.host' => $host,'mysql_status_history.port'=>$port]))->andFilterWhere(['>=', 'YmdHi', $start_time])->andFilterWhere(['<=', 'YmdHi', $end_time])->all();
            $os_chart_data = OsStatusHistory::find()->joinWith('servers')->where((['os_status_history.ip' => $host]))->andFilterWhere(['>=', 'YmdHi', $start_time])->andFilterWhere(['<=', 'YmdHi', $end_time])->all();

            return $this->render('chart', [
                'chart_data' => $chart_data,
                'os_chart_data' => $os_chart_data,
                'model' => $model,
                'time_interval' => $time_interval,
                'time_from'=>$time_from,
                'time_to'=>$time_to,
            ]);
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }

    }

}
